package com.stu.day14;

import java.util.Comparator;
import java.util.Objects;
import java.util.TreeSet;

/**
 * @author zy
 * @date 2025/2/13 09:58
 */
public class TreeSetDemo {
    public static void main(String[] args) {
        //1. 如果存储自定义对象类型的话,需要在构建TreeSet的时候,传入一个比较器
        //2. 或者直接让这个对象实现可比较接口java.lang.Comparable

        //根据价格进行降序排
        Comparator<Book> c = (b1, b2)->(int)(b2.getPrice() - b1.getPrice());

        TreeSet<Book> set = new TreeSet<>(c);
        Book b1 = new Book(1,"java",300.0d);
        Book b2 = new Book(2,"python",200.0d);
        Book b3 = new Book(3,"html",400.0d);
        Book b4 = new Book(4,"mysql",100.0d);
        Book b5 = new Book(5,"jdbc",500.0d);

        //不可重复 - 排序规则是根据price,如果后面有一样的价格,则拒绝添加
        Book b6 = new Book(10,"redis",300.0d);
        set.add(b1);
        set.add(b2);
        set.add(b3);
        set.add(b4);
        set.add(b5);
        set.add(b6);

        for (Book book : set) {
            System.out.println(book);
        }
    }
}

class Book{
    private Integer id;
    private String bookName;
    private Double price;

    public Book(){

    }
    public Book(Integer id,String bookName,Double price){
        this.id = id;
        this.bookName = bookName;
        this.price = price;
    }

    public Double getPrice() {
        return price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return Objects.equals(id, book.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Book{");
        sb.append("id=").append(id);
        sb.append(", bookName='").append(bookName).append('\'');
        sb.append(", price=").append(price);
        sb.append('}');
        return sb.toString();
    }
}